package com.google.code.drift.async_task;

import java.io.IOException;
import java.net.SocketTimeoutException;

import android.content.Context;
import android.os.AsyncTask;

import com.google.code.drift.api.AppSkyApp;
import com.google.code.drift.service.ServerConnection;
import com.google.code.drift.utils.DLog;
import com.google.code.drift.utils.JsonFactory;
import com.google.code.drift.utils.JsonParser;
import com.google.code.drift.utils.CommonUtils;

public class LoginTask extends AsyncTask<String, Object, Integer> {

	private Context context = null;
	private ServerConnection connection = null;

	private int timeOut = 30 * 1000;// 30秒

	public LoginTask(Context context) {
		this.context = context;
	}

	@Override
	protected Integer doInBackground(String... params) {
		return login(params[0]);
	}

	private int login(String param) {
		int resultFlag;
		String respond;
		AppSkyApp app = (AppSkyApp) context.getApplicationContext();
		String json = null;
		if (param.equals("")) {
			json = makeLoginJsonString(app);
		} else {
			json = param;
		}

		DLog.i("login Json: " + json);
		try {
			// 与服务器创建连接
			connection = ServerConnection.createConnection(app.getIp());
			respond = loginAndResult(json);
			DLog.i("login receive: " + respond);
			JsonParser jsonParser = new JsonParser(app.getMyInfo());
			resultFlag = jsonParser.parseLoginJson(respond);

			connection.setSocketTimeout(0);// 取消超时限制
		} catch (SocketTimeoutException e) {
			resultFlag = CommonUtils.LOGIN_TIMEOUT;
		} catch (IOException e) {
			DLog.i("异常！？！？");
			resultFlag = CommonUtils.LOGIN_ERROR;
		}
		return resultFlag;
	}

	private String loginAndResult(String loginMessage)
			throws SocketTimeoutException, IOException {
		connection.setSocketTimeout(timeOut);
		connection.sendMessage(loginMessage);
		return connection.readMessage();
	}

	private String makeLoginJsonString(AppSkyApp app) {
		JsonFactory jsonFactory = JsonFactory.getFactory();

		String loginJson = jsonFactory.makeUserLoginJson(
				app.getMyInfo().getUserId(), app.getMyInfo().getLatitude(),
				app.getMyInfo().getLongitude(), app.getMyInfo().getNick(),
				app.getMyInfo().getSex()).toJSONString();

		return loginJson;
	}


}
